# 导包
import pymysql


class DBTools(object):

    @staticmethod
    def __conn_mysql():
        # 创建连接对象
        conn = pymysql.connect(host="211.103.136.244", port=7061,
                               user="student", password="iHRM_student_2022",
                               database="ihrm", charset="utf8")
        return conn

    @staticmethod
    def query_one(sql):
        # 定义全局变量初始值为None
        my_conn = None
        cur = None
        try:
            # 创建游标对象
            my_conn = DBTools.__conn_mysql()
            cur = my_conn.cursor()
            # 执行SQL
            cur.execute(sql)
            # 获取查询结果
            result = cur.fetchone()  # 元组类型数据：((5.7.29),)
            # 返回结果
            return result
        except Exception as e:
            print(f"执行失败：{e}")
        finally:
            # 关闭游标
            cur.close()
            # 关闭连接
            my_conn.close()

    @staticmethod
    def db_uid(sql):
        my_conn = None
        cur = None
        try:
            # 创建游标对象
            my_conn = DBTools.__conn_mysql()
            cur = my_conn.cursor()
            # 执行SQL
            cur.execute(sql)
            # 提交事务
            my_conn.commit()
            # 显示影响行数
            return f"影响行数：{cur.rowcount}" # 可以不写
        except Exception as e:
            # 回滚事务
            print(f"执行失败：{e}")
            my_conn.rollback()
            print("回滚完毕")
        finally:
            # 关闭游标
            cur.close()
            # 关闭连接
            my_conn.close()

if __name__ == '__main__':
    # sql1 = """
    # delete from bs_user where mobile = "13812340132";
    # """
    # print(DBTools.db_uid(sql1))

    sql2 = """
    select version();
    """
    print(DBTools.query_one(sql2))







